﻿using System.Collections.Generic;
using System.Xml;
using MugenInjection.Infrastructure;
using MugenInjection.Xml.Interface;

namespace MugenInjection.Xml.Infrastructure
{
    /// <summary>
    /// Represents interface for access to xml element.
    /// </summary>
    public class XmlElementAdapter : IXmlElement
    {
        #region Fields

        private readonly XmlElement _xmlElement;

        #endregion

        #region Constructor

        /// <summary>
        /// Initializes a new instance of the <see cref="XmlElementAdapter"/> class.
        /// </summary>
        public XmlElementAdapter(XmlElement xmlElement)
        {
            Validate.ArgumentNotNull(xmlElement, "xmlElement");
            _xmlElement = xmlElement;
        }

        #endregion

        #region Implementation of IXmlElement

        /// <summary>
        /// Gets original element.
        /// </summary>
        public object Element
        {
            get { return _xmlElement; }
        }

        /// <summary>
        /// Gets element name.
        /// </summary>
        public string Name
        {
            get { return _xmlElement.Name; }
        }

        /// <summary>
        /// Gets attribute with specified name.
        /// </summary>
        /// <param name="name">Specified name.</param>
        /// <returns>An instance of <see cref="string"/>.</returns>
        public string GetAttribute(string name)
        {
            return _xmlElement.GetAttribute(name);
        }

        /// <summary>
        /// Gets xml element with specified name.
        /// </summary>
        /// <param name="name">Specified name.</param>
        /// <returns>An instance of <see cref="IXmlElement"/>.</returns>
        public IXmlElement GetNode(string name)
        {
            var xmlElement = _xmlElement[name];
            if (xmlElement == null) return null;
            return new XmlElementAdapter(xmlElement);
        }

        /// <summary>
        /// Gets xml elements with specified name.
        /// </summary>
        /// <param name="name">Specified name.</param>
        /// <returns>A series instances of <see cref="IXmlElement"/>.</returns>
        public IEnumerable<IXmlElement> GetNodes(string name)
        {
            foreach (object node in _xmlElement)
            {
                var xmlElement = node as XmlElement;
                if (xmlElement == null || !xmlElement.Name.Equals(name)) continue;
                yield return new XmlElementAdapter(xmlElement);
            }
        }

        #endregion
    }
}